<script setup>
import {getAllFlower, deleteFlowerById, starOrStopFlower, updateFlower,getFlowerByPage,addFlower} from "@/api/flower.js";
import {getAllCategory} from "@/api/category.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

const pageSelect = ref({
  page: 1,
  pageSize: 10,
  name: "",
  category: null,
  total: 0
});

// 花卉列表
const flowerList = ref([]);
const getFlowerList = async () => {
  //const res = await getAllFlower();
  console.log(pageSelect.value);
  const res = await getFlowerByPage(pageSelect.value);
  flowerList.value = res.data.flowers;
  pageSelect.value.total = res.data.total;
};
getFlowerList();
const getAllFlowerList = async () => {
  const res = await getAllFlower();
  pageSelect.value.total = res.data.length;
};
//getAllFlowerList();

// 分类列表
const categoryList = ref([]);
const getCategoryList = async () => {
  const res = await getAllCategory();
  categoryList.value = res.data;
};
getCategoryList();

// 删除花卉
const deleteFlower = async (row) => {
  ElMessageBox.confirm(
      `确定要删除 "${row.name}" 吗？`,
      "警告",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
  )
      .then(async () => {
        await deleteFlowerById(row.flowerId);
        ElMessage.success("删除成功");
        getFlowerList();
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};

// 修改花卉状态
const starOrStop = async (row) => {
  row.status = row.status === 1 ? 0 : 1;
  const res = await starOrStopFlower(row);
  ElMessage.success(res.data);
};

// 修改花卉 抽屉逻辑
const drawerVisible = ref(false);
const currentFlower = ref({});
const openEditDrawer = (flower) => {
  currentFlower.value = {...flower};
  drawerVisible.value = true;
};
const saveFlower = async () => {
  await updateFlower(currentFlower.value);
  ElMessage.success("修改成功");
  drawerVisible.value = false;
  await getFlowerList();
};

//添加花卉 弹窗
const addFlowerVisible = ref(false);
const addFlowerData = ref({
  name: "",
  description: "",
  price: 0,
  category: "",
  imageUrl: ""
});
const rules = {
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
  category: [{ required: true, message: "分类不能为空", trigger: "change" }]
};
const saveAddFlower = async () => {
 
  const formRef = addFlowerForm.value;
  if (!formRef) return;
  
  formRef.validate(async (valid) => {
    if (valid) {
      await addFlower(addFlowerData.value); // 调你的接口
      ElMessage.success("添加成功");
      addFlowerVisible.value = false;
      
      addFlowerData.value = {
        name: "",
        description: "",
        price: 0,
        category: "",
        imageUrl: ""
      };
    } else {
      ElMessage.error("请填写必填项");
    }
  });
};
const addFlowerForm = ref(null);
const handleClose = () => {
  addFlowerVisible.value = false;
};


// 捕获图片异常
const handleImageError = (event) => {
  event.target.src = 'https://tse4.mm.bing.net/th/id/OIP.09dxXiT3JsB5QIGGQCl1fgEyDL?w=1204&h=800&rs=1&pid=ImgDetMain'; // 替换为默认图片路径
};

// 分页
const handleSizeChange = (newSize) => {
  pageSelect.value.pageSize = newSize;
  pageSelect.value.page = 1;
  getFlowerList();
};
const handleCurrentChange = (newPage) => {
  pageSelect.value.page = newPage;
  getFlowerList();
};

//上传成功回调
const handleUpdateSuccess = (result) => {
  currentFlower.value.imageUrl = `${result.data}?t=${new Date().getTime()}`;
};
const handleAddSuccess = (result) => {
  addFlowerData.value.imageUrl = `${result.data}?t=${new Date().getTime()}`;
};

</script>

<template>
<div class="page-container">
  <h1 class="title">🌸 花卉管理列表</h1>
  
  <!-- 分类下拉选择框和名称输入框 -->
  <el-row class="filter-bar" justify="start" align="middle" style="margin-bottom: 20px;margin-left: 120px" >
    <el-col :span="6">
      <el-select v-model="pageSelect.category" placeholder="请选择分类" clearable style="width: 100%;">
        <el-option
            v-for="category in categoryList"
            :key="category.categoryName"
            :label="category.categoryName"
            :value="category.categoryName"
        />
      </el-select>
    </el-col>
    <el-col :span="6" style="margin-left: 20px;">
      <el-input
          v-model="pageSelect.name"
          placeholder="请输入名称"
          clearable
          style="width: 100%;"
      />
    </el-col>
    <el-col :span="4" style="margin-left: 20px;">
      <el-button type="primary" @click="getFlowerList">搜索</el-button>
    </el-col>
    <el-col :span="4" style="margin-left: -70px;">
      <el-button type="success" @click="addFlowerVisible=true">添加花卉</el-button>
    </el-col>
    
  </el-row>
 <!-- 花卉列表 -->
  <el-row class="flower-header" justify="space-between" align="middle">
    <el-col :span="3"><strong>名称</strong></el-col>
    <el-col :span="3"><strong>价格</strong></el-col>
    <el-col :span="3"><strong>销量</strong></el-col>
    <el-col :span="4"><strong>分类</strong></el-col>
    <el-col :span="4"><strong>图片</strong></el-col>
    <el-col :span="7"><strong>操作</strong></el-col>
  </el-row>
  
  <el-divider/>
  
  <el-row v-for="flower in flowerList" :key="flower.flowerId" class="flower-item" align="middle">
    <el-col :span="3">{{ flower.name }}</el-col>
    <el-col :span="3">¥{{ flower.price }}</el-col>
    <el-col :span="3">{{ flower.sales }}</el-col>
    <el-col :span="4">{{ flower.category }}</el-col>
    <el-col :span="4">
      <img :src="flower.imageUrl" alt="flower" style="width: 50px; height: 50px; border-radius: 50%;" @error="handleImageError"/>
    </el-col>
    <el-col :span="7">
      <el-button
          type="primary"
          size="small"
          :style="{
            backgroundColor: flower.status === 1 ? '#f56c6c' : '#6fc6ff',
            borderColor: flower.status === 1 ? '#f56c6c' : '#6fc6ff'
          }"
          @click="starOrStop(flower)"
      >
        {{ flower.status === 1 ? '禁售' : '起售' }}
      </el-button>
      
      <el-button type="success" size="small" @click="openEditDrawer(flower)">修改</el-button>
      <el-button type="danger" size="small" @click="deleteFlower(flower)">删除</el-button>
    </el-col>
  </el-row>
  <!-- 分页 -->
  <el-pagination
    style="margin-left: 150px"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="pageSelect.total"
    :current-page="pageSelect.page"
    :page-size="pageSelect.pageSize"
    :page-sizes="[10, 20]"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    class="pagination-bar"
/>


  
</div>


<!--抽屉-->
<el-drawer
    v-model="drawerVisible"
    title="修改花卉信息"
    direction="rtl"
    size="30%"
>
  <div style="text-align: center; margin-bottom: 20px;">
    <img
        v-if="currentFlower.imageUrl" :src="currentFlower.imageUrl" alt="花卉图片"
        style="width: 200px; height: 200px; object-fit: cover; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1)"
    />
    <div style="margin-top: 10px;">
      <el-upload class="upload-demo" action="/api/upload" name="file" :show-file-list="false"
                 :on-success="handleUpdateSuccess">
        <el-button type="primary">点击上传新图片</el-button>
      </el-upload>
    </div>
  </div>
  
  <el-form :model="currentFlower" label-width="100px">
    <el-form-item label="花卉ID">
      <el-input v-model="currentFlower.flowerId" disabled/>
    </el-form-item>
    <el-form-item label="名称">
      <el-input v-model="currentFlower.name"/>
    </el-form-item>
    <el-form-item label="描述">
      <el-input v-model="currentFlower.description" type="textarea"/>
    </el-form-item>
    <el-form-item label="价格">
      <el-input v-model="currentFlower.price" type="number"/>
    </el-form-item>
    <el-form-item label="销量">
      <el-input v-model="currentFlower.sales" type="number"/>
    </el-form-item>
    <el-form-item label="分类">
      <el-select v-model="currentFlower.category" placeholder="请选择分类">
        <el-option
            v-for="category in categoryList"
            :key="category.categoryId"
            :label="category.categoryName"
            :value="category.categoryId"
        />
      </el-select>
    </el-form-item>
  </el-form>
  
  <div style="text-align: right; margin-top: 20px;">
    <el-button @click="drawerVisible = false">取消</el-button>
    <el-button type="primary" @click="saveFlower">保存</el-button>
  </div>
</el-drawer>


<!--添加花卉-->
<el-dialog
    v-model="addFlowerVisible"
    title="添加花卉"
    width="30%"
    :before-close="handleClose"
>
  <el-form :model="addFlowerData" :rules="rules" ref="addFlowerForm" label-width="80px">
    <!-- 图片预览 -->
    <el-form-item>
      <div style="text-align: center; margin-bottom: 10px;">
        <img
            v-if="addFlowerData.imageUrl"
            :src="addFlowerData.imageUrl"
            alt="预览图片"
            style="width: 150px; height: 150px; object-fit: cover; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1)"
        />
      </div>
    </el-form-item>
    
    <!-- 图片上传 -->
    <el-form-item label="图片">
      <el-upload
          class="upload-demo"
          action="/api/upload"
          name="file"
          :show-file-list="false"
          :on-success="handleAddSuccess"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>
    </el-form-item>
    
    <!-- 其他表单项 -->
    <el-form-item label="名称" prop="name">
      <el-input v-model="addFlowerData.name" placeholder="请输入名称" />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input v-model="addFlowerData.price" type="number" placeholder="请输入价格" />
    </el-form-item>
    <el-form-item label="分类" prop="category">
      <el-select v-model="addFlowerData.category" placeholder="请选择分类" clearable>
        <el-option
            v-for="category in categoryList"
            :key="category.categoryName"
            :label="category.categoryName"
            :value="category.categoryName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="描述">
      <el-input v-model="addFlowerData.description" type="textarea" placeholder="请输入描述" />
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="addFlowerVisible = false">取消</el-button>
      <el-button type="primary" @click="saveAddFlower">保存</el-button>
    </div>
  </template>
</el-dialog>


</template>

<style scoped>
.page-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px 20px;
  background: #fafafa;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  min-height: 1000px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.flower-header {
  padding: 8px 0;
  font-size: 16px;
  background: #f0f2f5;
  border-radius: 6px;
}

.flower-item {
  margin-bottom: 12px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}
</style>
